import React, { useEffect } from 'react';
import { Button } from 'antd';
import XTerm from '../components/Terminal/XTerm';
import { useTerminalStore } from '../stores/terminalStore';
import { useConnectionsStore } from '../stores/connectionsStore';
import './TerminalPage.css';
import { message } from 'antd';

const TerminalPage: React.FC = () => {
  const {
    sessions,
    activeSessionId,
    setActiveSession,
    closeSession,
    getActiveSession,
  } = useTerminalStore();

  const { connections, connectionAuths } = useConnectionsStore();

  // 处理终端数据发送
  const handleTerminalData = (sessionId: string, data: string) => {
    const session = sessions.find(s => s.id === sessionId);
    if (!session) return;

    // TODO: 通过SSH服务发送数据
    // window.electronAPI?.ssh.sendData(session.connectionId, data);
    console.log('Terminal data:', sessionId, data);
  };

  // 关闭会话
  const handleCloseSession = (sessionId: string, e: React.MouseEvent) => {
    e.stopPropagation();

    const session = sessions.find(s => s.id === sessionId);
    if (!session) return;

    // TODO: 断开SSH连接
    // window.electronAPI?.ssh.disconnect(session.connectionId);
    closeSession(sessionId);

    message.success('终端会话已关闭');
  };

  // 跳转连接管理
  const goToConnections = () => {
    // 这里假设有导航API
    // window.electronAPI?.nav.navigate('/connections');
    console.log('跳转到连接管理页面');
  };

  const activeSession = getActiveSession();

  return (
    <div className="terminal-page">
      {/* 终端标签页栏 */}
      <div className="terminal-tabs-container">
        <div className="terminal-tabs">
          {sessions.map((session) => (
            <div
              key={session.id}
              className={`terminal-tab ${activeSessionId === session.id ? 'active' : ''}`}
              onClick={() => setActiveSession(session.id)}
            >
              <div className="terminal-tab-title">
                <span>💻</span>
                <span>{session.title}</span>
              </div>
              <div
                className="terminal-tab-close"
                onClick={(e) => handleCloseSession(session.id, e)}
              >
                ✕
              </div>
            </div>
          ))}
        </div>

        {/* 新建会话按钮 */}
        <div
          className="terminal-add-btn"
          onClick={goToConnections}
          title="新建终端会话"
        >
          +
        </div>
      </div>

      {/* 终端内容区域 */}
      <div className="terminal-pane-container">
        {sessions.length === 0 ? (
          <div className="terminal-empty">
            <div className="terminal-empty-icon">💻</div>
            <h3 className="terminal-empty-title">暂无活动终端</h3>
            <p className="terminal-empty-description">
              请先在连接管理中创建并连接到服务器
            </p>
            <Button
              type="primary"
              onClick={goToConnections}
              style={{ marginTop: 16 }}
            >
              前往连接管理
            </Button>
          </div>
        ) : (
          sessions.map((session) => {
            const connection = connections.find(c => c.id === session.connectionId);
            if (!connection) return null;

            return (
              <div
                key={session.id}
                className={`terminal-pane ${activeSessionId === session.id ? 'active' : ''}`}
              >
                <XTerm
                  connectionId={connection.id}
                  onData={(data) => handleTerminalData(session.id, data)}
                />
              </div>
            );
          })
        )}
      </div>
    </div>
  );
};

export default TerminalPage;